package dawn.jxufe.community.event;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import dawn.jxufe.community.entity.DiscussPost;
import dawn.jxufe.community.entity.Event;
import dawn.jxufe.community.entity.Message;
import dawn.jxufe.community.service.DiscussPostService;
import dawn.jxufe.community.service.ElasticsearchService;
import dawn.jxufe.community.service.MessageService;
import dawn.jxufe.community.util.CommunityConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author dawn21
 * @version 1.0
 * @date 2022/8/17 20:51
 * @component 事件消费者。被动调用。
 */

@Component
public class EventConsumer implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    // 处理事件后最终是要给某个用户发送一条消息(某人评论了你的帖子)，然后往message表里插入一条数据。

    @Autowired
    private MessageService messageService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.bucket.community.share.name}")
    private String shareBucketName;

    @Value("${aliyun.bucket.community.share.url}")
    private String shareBucketUrl;

    // 可以执行定时任务的线程池，quartz用于分布式。
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        // 消息的内容不为空，是JSON格式的字符串，将字符串恢复成相关格式的数据。
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息的格式错误！");
            return;
        }

        // 发送站内通知，构造message。
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId()); // 事件触发者。
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());


        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }

        message.setContent(JSONObject.toJSONString(content)); // 将事件中的数据给content(map)，然后给message。
        messageService.addMessage(message); // 将message存入数据库。
    }

    // 消费发帖事件
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record){

        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        // 消息的内容不为空，是JSON格式的字符串，将字符串恢复成相关格式的数据。
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息的格式错误！");
            return;
        }

        // 消费帖子才是存帖子到elasticsearch服务器中。
        // 从消息中拿到帖子，存到elasticsearch服务器中。
        DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
        elasticsearchService.saveDiscussPost(discussPost);

    }


    // 消费删帖事件
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record){

        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        // 消息的内容不为空，是JSON格式的字符串，将字符串恢复成相关格式的数据。
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息的格式错误！");
            return;
        }
        elasticsearchService.deleteDiscussPost(event.getEntityId());

    }

/*    // 消费share事件
    @KafkaListener(topics = {TOPIC_SHARE})
    public void handleShareMessage(ConsumerRecord record){

        if (record == null || record.value() == null) {
            logger.error("消息的内容为空！");
            return;
        }

        // 消息的内容不为空，是JSON格式的字符串，将字符串恢复成相关格式的数据。
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            logger.error("消息的格式错误！");
            return;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName"); // xxx
        String suffix = (String) event.getData().get("suffix"); // .png

        //fileName = fileName + suffix; // xxx.png

        // 还是先生成在本地，再上传。
        // 需要修改地址.
        String cmd = wkImageCommand + " --quality 75 "
                + htmlUrl + " " + wkImageStorage + "/" + fileName + suffix;

        try {
            Runtime.getRuntime().exec(cmd); // 执行
            logger.info("生成长图成功：" + cmd);
        } catch (IOException e) {
            logger.error("生成长图失败: " + e.getMessage());
        }

        // 启用定时器，监视照片生成，一旦生成则上传到云服务器。
        UploadTask task = new UploadTask(fileName, suffix);
        Future future = threadPoolTaskScheduler.scheduleAtFixedRate(task, 500);
        task.setFuture(future);

    }*/

/*    class UploadTask implements Runnable {
        private String fileName; // 文件名称
        private String suffix; // 文件后缀
        private Future future; // 启动任务的返回值，可以用来停止定时器。
        private long startTime; // 开始时间
        private int uploadTimes; // 上传次数
        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }
        public void setFuture(Future future) {
            this.future = future;
        }
        @Override
        public void run() { // 上传的逻辑，500毫秒执行一次，直到停止。
            // 生成图片失败
            if (System.currentTimeMillis() - startTime > 30000) {
                logger.error("执行时间过长，终止任务：" + fileName);
                future.cancel(true);
                return;
            }
            // 上传失败
            if (uploadTimes >= 3) {
                logger.error("上传次数过多，终止任务：" + fileName);
                future.cancel(true);
            }
            // 本地照片文件路径。
            String path = wkImageStorage + "/" + fileName + suffix;
            //MultipartFile file = (MultipartFile) new File(path);
            FileInputStream fileInputStream = null;
            long size = 0;
            try {
                fileInputStream = new FileInputStream(path);
                size = fileInputStream.getChannel().size();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (size > 0) {
                logger.info(String.format("开始第%d次上传[%s].", ++uploadTimes, fileName));
                try {
                    // headerImage.transferTo(dest);
                    // community-header-lxliujx xxx.png 照片输入流
                    // https://community-header-lxliujx.oss-cn-hangzhou.aliyuncs.com/xxxxxx.png
                    PutObjectRequest putObjectRequest = new PutObjectRequest(shareBucketName, fileName + "." + suffix, fileInputStream);
                    Map<String, String> map = new HashMap<>();
                    //设置为公开读可见
                    map.put("x-oss-object-acl","public-read");
                    putObjectRequest.setHeaders(map);
                    PutObjectResult putResult = ossClient.putObject(putObjectRequest);
                    logger.info("====上传成功！====");
                    //fileInputStream.close();
                    future.cancel(true);
                } finally {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ossClient.shutdown();
                }
            }
        }
    }*/

}
